/*******************************************************************************
 * @(#)CrossDomainServerInterceptor.java 2019年08月29日 17:11
 * Copyright 2019 upbos.com. All rights reserved.
 *******************************************************************************/
package com.upbos.sso.plugin;

import com.upbos.sso.entity.SsoContext;
import com.upbos.sso.Constants;
import com.upbos.sso.filter.ChainRet;
import com.upbos.sso.mgr.TokenManager;
import com.upbos.sso.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <b>Application name：</b> CrossDomainServerInterceptor.java <br>
 * <b>Application describing： </b> <br>
 * <b>Copyright：</b> Copyright &copy; 2019 upbos.com 版权所有。<br>
 * <b>Company：</b> upbos.com <br>
 * <b>@Date：</b> 2019年08月29日 17:11 <br>
 * <b>@author：</b> <a href="mailto:Jason@miyzh.com"> Jason </a> <br>
 * <b>@version：</b>V5.0.0 <br>
 */
@Slf4j
public class SsoServerTokenInterceptor implements Interceptor {

    /**
     * 跨域登录验证服务器地址
     */
    private String tokenServerUrl = "/**/sso/getToken.do";


    public void setTokenServerUrl(String tokenServerUrl) {
        this.tokenServerUrl = tokenServerUrl;
    }

    @Override
    public ChainRet preHandle(HttpServletRequest request, HttpServletResponse response, SsoContext ssoContext) {

        //如果请求URL不是获取token，则不进入此拦截器工作
        PathMatcher matcher = new AntPathMatcher();
        if (!matcher.match(tokenServerUrl, request.getRequestURI())) {
            return ChainRet.NEXT;
        }

        TokenManager tokenManager = new TokenManager(ssoContext.getSsoManager());
        ServletUtils.write(response, tokenManager.get(request));


        return ChainRet.BREAK;
    }

    @Override
    public int getPriority() {
        return -999;
    }

    @Override
    public String getName() {
        return Constants.INTERCEPTOR_SSO_SERVER_TOKEN;
    }
}
